package com.education.pojo;


import sun.misc.BASE64Decoder;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * 邓恒君
 * 显示头像的实体类
 * Created by Administrator on 2018/5/7.
 */
public class ImgHead {
    private static String URL1 = "\\img\\head";
    private static String URL2 = "\\img\\userhead";
    private String headname = "";
    //获取图片
    public static String[] getImgHead(String url){
        File file = new File(url+URL1);
        if(file.isDirectory()){
            String[] name = file.list();
            return name;
        }else{
            return null;
        }
    }

    //存储图片
    public static String setImgHead(String base64Img,String url1){
        String imgsrc="";
        if(base64Img==null){
            return null;
        }else{
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                byte[] b = decoder.decodeBuffer(base64Img);
                for (int i = 0; i < b.length; ++i) {
                    if (b[i] < 0) {// 调整异常数据
                        b[i] += 256;
                    }
                }
                // 生成文件名
                String files = new SimpleDateFormat("yyyyMMddHHmmssSSS")
                        .format(new Date())
                        + (new Random().nextInt(9000) % (9000 - 1000 + 1) + 1000)
                        + ".png";
                // 生成文件路径
//                String filename =url+URL+files;
                String filename2 = url1+URL2+"\\"+files;
                imgsrc = filename2;
                // 生成文件
                File imageFile1 = new File(filename2);
//                imageFile.createNewFile();
//                if(!imageFile.exists()){
//                    imageFile.createNewFile();
//                }
                OutputStream imageStream1 = new FileOutputStream(imageFile1);
                imageStream1.write(b);
                imageStream1.flush();
                imageStream1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return imgsrc;
        }
    }

    //删除图片
    public static int deleteUserHead(String name,String url1){
        String filename2 = url1+URL2+"\\"+name;
        File imageFile1 = new File(filename2);
        imageFile1.delete();
        return 1;
    }

//    public static InputStream getImg(String str)throws IOException{
//        File file = new File(str);
//        InputStream stream = new FileInputStream(file);
//        return stream;
//    }

}
